package dac.sort.core;

public class CountingSort implements Sort{

	public int[] sort(int[] array, int sortType) {
		int[] sorted = new int[array.length];
		int max = array[0];
		int min = array[0];
		int size = array.length;
		for (int i = 1; i < size; i++) {
			if(array[i] > max)
				max = array[i];
			if(array[i] < min)
				min = array[i];
		}
		
		int counting = max-min+1;
		int[] c = new int[counting];
		for (int i = 0; i < size; i++) {
			c[array[i]-min] ++;
		}
		if(sortType == SortType.ASC)
			for (int i = 1; i < counting; i++) {
				c[i] = c[i]+c[i-1];
			}
		else
			for (int i = counting-2; i >= 0; i--) {
				c[i] = c[i]+c[i+1];
			}
		
		for (int i = size-1; i >= 0; i--) {
			sorted[c[array[i]-min]-1] = array[i];
			c[array[i]-min] --;
		}
		return sorted;
	}
	
	public static void main(String[] args) {
		Sort s = new CountingSort();
		int[] array = new int[]{3,1,2,5,5,5,7,8,9,9,4,5,3,34,6,3,6,8,9};
		int[] arr= s.sort(array, 2);
		int[] arr1= s.sort(array, 1);
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i]+" ");
		}
		System.out.println();
		for (int i = 0; i < arr1.length; i++) {
			System.out.print(arr1[i]+" ");
		}
	}

}
